package com.joseph.websocket.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GzipUtil {


    public static byte[] uncompress(byte[] bytes) {
        if (bytes == null || bytes.length == 0) {
            return null;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayInputStream in = new ByteArrayInputStream(bytes);
        try {
            GZIPInputStream ungzip = new GZIPInputStream(in);
            byte[] buffer = new byte[256];
            int n;
            while ((n = ungzip.read(buffer)) >= 0) {
                out.write(buffer, 0, n);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return out.toByteArray();
    }

    public static byte[] compress(String str, String encoding) {
        if (str == null || str.length() == 0) {
            return null;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        GZIPOutputStream gzip;
        try {
            gzip = new GZIPOutputStream(out);
            gzip.write(str.getBytes(encoding));
            gzip.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return out.toByteArray();
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        String a = "{\\\"percent\\\":100,\\\"whiteList\\\":[\\\"25919648\\\",\\\"20365672\\\",\\\"22462505\\\",\\\"58239049\\\",\\\"73753586\\\",\\\"53810415\\\",\\\"74110111\\\",\\\"71924378\\\",\\\"72169703\\\",\\\"79533520\\\",\\\"65442741\\\"\" +\n" +
                "                \",\\\"53645944\\\",\\\"107303725\\\",\\\"140914482\\\",\\\"58945859\\\"],\\\"nlpUrl\\\":\\\"http://10.0.118.91:9999/quer\" +\n" +
                "                \"y\\\",\\\"httpOrDubbo\\\":\\\"dubbo\\\"}";
        System.out.println(a.length());
        byte [] data = compress(a,"utf-8");
        System.out.println(new String(uncompress(data), "utf-8").length());
    }

}
